package com.happy.qademo.websheet.controller;

import com.happy.qademo.websheet.common.CommonResVo;
import com.happy.qademo.websheet.entity.UserInfoEntity;
import com.happy.qademo.websheet.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import java.time.LocalDateTime;


@Slf4j
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController //定义为rest类型的控制器
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${admin.email:adminAccount}")
    private String adminEmail;

    @PostMapping("/user/register") //定义post请求
    public CommonResVo userRegister(String userName,String password,String email) throws Exception {
        String nickName = userName;
        log.info("register, userName:{}, psd:{}, email:{}, nickName:{}",userName,password,email,nickName);
        if(!StringUtils.hasText(userName)||!StringUtils.hasText(password)){
            return CommonResVo.fail("PARAM_INVALID","Username or password could not be empty!");
        }
        //验证用户名是否已存在
        if (!userService.checkUserByName(userName)) {
            return CommonResVo.fail("DATA_EXIST","Username is already exist!");
        }
       
        //用户密码存表时，要做加密处理，可以直接使用spring提供的DigestUtils工具类生成32位MD5字符串
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        LocalDateTime now = LocalDateTime.now();
        UserInfoEntity userInfo = new UserInfoEntity(userName,passwordMd5,email,nickName);
        
        if (adminEmail.equals(email)) {
            userInfo.setStatus(1);
        }else{
            userInfo.setStatus(0);
        }
        userInfo.setCreateTime(now);
        userInfo.setUpdateTime(now);
        userService.addUserInfo(userInfo);
        return CommonResVo.success();
    }



    @PostMapping("/user/changePassword")
    public CommonResVo changePassword(@RequestParam String userName, @RequestParam String oldPassword, @RequestParam String newPassword) throws Exception {
        log.info("changePassword, userName:{}, oldPassword:{}, newPassword:{}", userName, oldPassword, newPassword);

        // 验证用户名和旧密码是否为空
        if (!StringUtils.hasText(userName) || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            return CommonResVo.fail("PARAM_INVALID", "Username, old password or new password could not be empty!");
        }
        
        // 验证用户名是否存在
        UserInfoEntity userInfo = userService.findUserByName(userName);
        if (userInfo == null) {
            return CommonResVo.fail("DATA_NOT_EXIST", "Username does not exist!");
        }

        // 验证旧密码是否正确
        String oldPasswordMd5 = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!oldPasswordMd5.equals(userInfo.getPassword())) {
            return CommonResVo.fail("PASSWORD_ERROR", "Old password is incorrect!");
        }

        // 对新密码进行加密
        String newPasswordMd5 = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        userInfo.setPassword(newPasswordMd5);
        userInfo.setUpdateTime(LocalDateTime.now());

        // 更新用户信息
        userService.updateUserInfo(userInfo);

        return CommonResVo.success();
    }

    @PostMapping("/user/login") //定义post请求
    public CommonResVo userLogin(String userName, String password, HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        //验证用户名是否已存在
        log.info("login, userName:{},psd:{}",userName,password);
        if (!StringUtils.hasText(userName) || !StringUtils.hasText(password)) {
            log.warn("username or password could not be empty!");
            return CommonResVo.fail("PARAM_INVALID","Username or password could not be empty!");
        }
        UserInfoEntity userInfoEntity = userService.findUserByName(userName);
        if(ObjectUtils.isEmpty(userInfoEntity)){
            log.warn("Username is not exit!");
            return CommonResVo.fail("DATA_NOT_EXIST","Username is not exit!");
        }
        //用户密码存表时，要做加密处理，可以直接使用spring提供的DigestUtils工具类生成32位MD5字符串
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!passwordMd5.equals(userInfoEntity.getPassword())){
            log.warn("password is invalid!");
            return CommonResVo.fail("PARAM_INVALID","password is invalid!");
        }

        if(1==userInfoEntity.getStatus()){
            // request.getSession().setAttribute("userInfo",userInfoEntity);
            HttpSession session = request.getSession();
            session.setAttribute("userInfo", userInfoEntity);
            session.setMaxInactiveInterval(7200); 
            // 设置 Cookie
            Cookie userCookie = new Cookie("sheetUserInfo", userName);
            // 设置 Cookie 的有效期，这里设置为 1 小时（3600 秒）
            userCookie.setMaxAge(7200); 
            // 设置 Cookie 的作用域
            userCookie.setPath("/"); 
            // 将 Cookie 添加到响应中
            response.addCookie(userCookie);
            return CommonResVo.success();
        }else {
            return CommonResVo.fail("LIMITED_PERMISSIONS","Permissions are limited, please contact the administrator!");
        }
    }

    @GetMapping("login")
    public ModelAndView login() {

        return new ModelAndView("login", "login", "");
    }

    @GetMapping("register")
    public ModelAndView register() {

        return new ModelAndView("register", "register", "");
    }

    // 退出登录接口
    @RequestMapping("/user/logout")
    public CommonResVo userLogout(HttpServletRequest request) {
        try {
            // 获取当前会话
            request.getSession().invalidate();
            log.info("User logged out successfully.");
            return CommonResVo.success();
        } catch (Exception e) {
            log.error("Error occurred during logout: {}", e.getMessage(), e);
            return CommonResVo.fail("LOGOUT_ERROR", "An error occurred during logout.");
        }
    }
}
